import sys


def get_csv_names():
    with open("../evaluation_dist/dist.txt") as f:
        lines = f.readlines()

    lines = lines[1:]
    sizes = []
    csv_names = []
    for line in lines:
        a = line.split()[4]
        if 'G' in a:
            sizes.append(float(a[:-1]))
            csv_name = line.split()[8]
            csv_names.append(csv_name)
        elif 'M' in a:
            sizes.append(float(a[:-1])/1024)
            csv_name = line.split()[8]
            csv_names.append(csv_name)
        elif 'K' in a:
            sizes.append(float(a[:-1])/(1024*1024))
            csv_name = line.split()[8]
            csv_names.append(csv_name)
        else:
            # sizes.append(0)
            pass

    return csv_names, sizes


def generate_start_stop(start, stop):
    csvnames, _ = get_csv_names()
    filenames_str = ""
    for i in range(start, stop):
        filenames_str += csvnames[i] + ' '

    f = open('./scripts/analyse_workloads' + str(start) + '_' + str(stop) + '.sh', 'w')
    sys.stdout = f

    print('#!/bin/bash')
    print('start_time=$(date +%s)')
    print('')

    print('cd ../learned-leveldb/')
    print('')
    print('path=../data/ebs_segment_io_records/AY283G_2022-01-01_00:00:00_2022-01-02_00:00:00/device/')
    print('')

    print('for filename in %s; do' % filenames_str)
    print('    data_path=${path}${filename}')
    print('    python ./scripts/analyseWl_single_in2periodSettings.py $data_path &')
    print('done\n')

    print('wait')
    print('end_time=$(date +%s)')
    print('cost_time=$((end_time-start_time))')
    print('echo "$0" "运行时间：$((cost_time/60))min $((cost_time%60))s"')

    f.close()


if __name__ == "__main__":
    # for i in range(100, 10000)

    # 生成各个start和step的python脚本
    seps = [0, 5, 15, 30, 50, 100]

    # seps = list(range(100, 5455, 100))

    # 生成批量运行python脚本的sh脚本
    script_name = './scripts/step0_analyse_workloads.sh'
    with open(script_name, 'w') as f:
        f.write('#!/bin/bash\n')
        f.write('start_time=$(date +%s)\n')

    for i in range(len(seps)-1):
        generate_start_stop(seps[i], seps[i+1])

        # 生成批量运行python脚本的sh脚本
        with open(script_name, 'a') as f:
            f.write("chmod +x ./scripts/analyse_workloads%d_%d.sh\n" % (seps[i], seps[i+1]))
            f.write("./scripts/analyse_workloads%d_%d.sh\n" % (seps[i], seps[i+1]))

    with open(script_name, 'a') as f:
        f.write('end_time=$(date +%s)\n')
        f.write('cost_time=$((end_time-start_time))\n')
        f.write('echo "$0" "运行时间：$((cost_time/60))min $((cost_time%60))s"')
